package com.woniu.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.entity.Dept;
import com.woniu.entity.User;
import com.woniu.entity.response.ResponseEntity;
import com.woniu.entity.vo.LoginUser;
import com.woniu.entity.vo.PageUser;
import com.woniu.entity.vo.RegisterUser;
import com.woniu.entity.vo.UserExcel;
import com.woniu.exception.controllerException.AccountExistException;
import com.woniu.exception.controllerException.NoMatchUserException;
import com.woniu.exception.controllerException.RePasswordInvalidException;
import com.woniu.security.JwtUtil;
import com.woniu.service.IUserService;
import com.woniu.util.ExcelResponseHeaderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hyl
 * @since 2022-08-28
 */
@RestController
@RequestMapping("/brain/user")
@CrossOrigin(allowCredentials = "true", originPatterns = "*")
public class UserController {
    @Autowired
    private IUserService userService;

    @Value("${user.picUploadPath}")
    private String picPath;

    @Autowired
    private JwtUtil jwtUtil;

    /*/**
     *@description 用户名密码登录验证
     *@params [user]
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/login")
    public ResponseEntity userLoginWithPassword(@RequestBody @Valid LoginUser loginUser) throws JsonProcessingException {
        User user = new User();
        user.setAccount(loginUser.getAccount());
        user.setPassword(loginUser.getPassword());
        List<User> userList = userService.getByAnyUser(user);

        if (userList.isEmpty()) {
            throw new NoMatchUserException("用户名或密码错误");
        }
        User user1 = userList.get(0);
        Map<String, String> map = new ConcurrentHashMap<>();
        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(user1);
        map.put("user", userJson);
        map.put("token", jwtUtil.createToken(user1));
        return ResponseEntity.success(map);
    }

    /*/**
     *@description 条件查询用户
     *@params [user]
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/list")
    public ResponseEntity getUserOnCondition(@RequestBody(required = false) User user) {
//        if (user == null) {
//            User user1 = new User();
//            user1.setUserStatus("y");
//            return ResponseEntity.success(userService.getByAnyUser(user1));
//        }
        return ResponseEntity.success(userService.getByAnyUser(user));
    }

    /*/**
     *@description 分页条件查询用户
     *@params [pageUser]
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/pageList")
    public ResponseEntity getUserOnConditionWithPage(@RequestBody PageUser pageUser) {
        if (pageUser.getP() == null || pageUser.getP() == 0) {
            pageUser.setP(1);
        }
        if (pageUser.getPageSize() == null || pageUser.getPageSize() == 0) {
            pageUser.setPageSize(10);
        }
//        if (pageUser.getUser() == null) {
//            User user = new User();
//            user.setUserStatus("y");
//            pageUser.setUser(user);
//        }
        return ResponseEntity.success(userService.getByAnyUserWithPage(pageUser.getP(), pageUser.getPageSize(), pageUser.getUser()));
    }

    /*/**
     *@description 增加用户(注册)
     *@params [user]
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/add")
    public ResponseEntity addUser(@RequestBody @Valid RegisterUser registerUser) {
        if (!Objects.equals(registerUser.getRePassword(), registerUser.getUser().getPassword())) {
            throw new RePasswordInvalidException("两次密码不相同");
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account", registerUser.getUser().getAccount());
        if (userService.getOne(wrapper) != null) {
            throw new AccountExistException("账号已存在");
        }
        User user = new User();
        user.setEntryDate(LocalDateTime.now().toString());
        user.setUserStatus("y");
        userService.save(registerUser.getUser());
        return ResponseEntity.success(registerUser.getUser());
    }

    /*/**
     *@description 根据id查询用户信息
     *@params [userId]
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/get/{userId}")
    public ResponseEntity getUserByUserId(@PathVariable("userId") Integer userId) {
        return ResponseEntity.success(userService.getByUserId(userId));
    }

    /*/**
     *@description 上传user头像,路径在本地，还需要改
     *@params []
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/upload/{userId}")
    public ResponseEntity uploadUserPic(MultipartFile file, @PathVariable Integer userId) {
        String type = file.getContentType();
        String originalFilename = file.getOriginalFilename();

        //todo 检验图片格式
        String path = picPath + "/" + UUID.randomUUID() + Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        try {
            file.transferTo(new File(path));
            UpdateWrapper wrapper = new UpdateWrapper();
            wrapper.eq("user_id", userId);
            User user = new User();
            user.setUserPic(path.substring(path.lastIndexOf("/")));
            userService.update(user, wrapper);
            return ResponseEntity.success(path.substring(path.lastIndexOf("/")));
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.fail(null);
        }
    }

    /*/**
     *@description 根据userId更新user
     *@params [user]
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/30
     */
    @RequestMapping("/update")
    public ResponseEntity updateUser(@RequestBody User user) {
        userService.updateById(user);
        return ResponseEntity.success(null);
    }

    /*/**
     *@description 返回所有部门人数
     *@params []
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/31
     */
    @RequestMapping("/count/dept")
    public ResponseEntity countUserByDept() {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.groupBy("dept_id");
        List<User> userList = userService.getByAnyUser(null);
        List<Dept> deptList = userList.stream().map(User::getDept).distinct().collect(Collectors.toList());
        Map<String, Integer> map = new ConcurrentHashMap<>();
        for (Dept dept : deptList) {
            QueryWrapper wrapper1 = new QueryWrapper();
            wrapper1.eq("dept_id", dept.getDeptId());
            map.put(dept.getDeptName(), (int) userService.count(wrapper1));
        }
        return ResponseEntity.success(map);
    }

    /*/**
     *@description 返回user性别和人数
     *@params []
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/31
     */
    @RequestMapping("/count/gender")
    public ResponseEntity countUserByGender() {
        QueryWrapper wrapper = new QueryWrapper();
        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper.eq("gender", "男");
        wrapper1.eq("gender", "女");
        Map<String, Integer> map = new ConcurrentHashMap<>();
        map.put("男", (int) userService.count(wrapper));
        map.put("女", (int) userService.count(wrapper1));
        return ResponseEntity.success(map);
    }

    /*/**
     *@description 导出userExcel 可按条件导出
     *@params []
     *@return_value com.woniu.entity.response.ResponseEntity
     *@author hyl
     *@date 2022/8/31
     */
    @RequestMapping("/download")
    public void downloadExcel(@RequestBody(required = false) User user, HttpServletResponse response) throws IOException {
        List<User> userList = userService.getByAnyUser(user);
        List<UserExcel> userExcels = new CopyOnWriteArrayList<>();
        for (User user1 : userList) {
            UserExcel userExcel = new UserExcel();
            userExcel.setUserName(user1.getUserName());
            userExcel.setUserTel(user1.getUserTel());
            userExcel.setGender(user1.getGender());
            userExcel.setSalary(user1.getSalary());
            userExcel.setEntryDate(user1.getEntryDate());
            userExcel.setLeaveDate(user1.getLeaveDate());
            userExcel.setUserEmail(user1.getUserMail());
            userExcel.setDeptName(user1.getDept().getDeptName());
            userExcel.setStatus(user1.getLeaveDate() == null || user1.getLeaveDate().trim().equals("") ? "在职" : "离职");
            userExcels.add(userExcel);
        }
        ExcelResponseHeaderUtil.setExcelRespProp(response, "员工表");
        EasyExcel.write(response.getOutputStream())
                .head(UserExcel.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("员工表")
                .doWrite(userExcels);
    }
}
